<?php

/**
 * 财付通插件
 * censhuixing
 * 2014-08-05
 */
class tenpay
{

	var $payment = array(
	//'key'=>'e82573dc7e6136ba414f2e2affbe39fa',//交易安全校验码
	'key'=>'789abb1fd1f556fd316e4669165eb8bd',//交易安全校验码
	'partner'=>'1220325801',//商户号
	);

	//b7d02cbde2ff8ec9fb249ba43ed639ab
	//1220325801

	/**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */
	function tenpay()
	{
	}

	/**
     * 生成支付代码
     * @param   array   $order      订单信息
     * @param   array   $payment    支付方式信息
     */
	function get_code($order)
	{

		/* 版本号 */
		$version = '1.0';

		/* 编码标准 */
		$input_charset = 'UTF-8';

		/* 银行类型:支持纯网关和财付通 */
		$bank_type_value = '0';

		/* 总金额 */
		/* 商品价格（包含运费），以分为单位 */
		$total_fee = floatval($order['trans_amount']) * 100;

		/* 交易参数 */
		$parameter = array(
		'partner'           => $this->payment['partner'],     //商户号
		'out_trade_no'      => $order['trans_code'],          //外部交易号
		'total_fee'         => $total_fee,                    //交易金额
		'return_url'        => $order['return_url'],          //支付结果页面
		'notify_url'        => $order['notify_url'],          //异步通知页面
		'body'              => '万菱家饰网订单('.$order['trans_code'].')', //商品描述
		'bank_type'         => $bank_type_value,              //银行类型，默认为财付通
		'spbill_create_ip'  => real_ip(),                     //客户端IP
		'fee_type'          => 1,                             //现金支付币种
		'subject'           => '性福之家（'.$order['trans_code'].')',//商品名称，（中介交易时必填）
		'input_charset'     => $input_charset,                //字符集
		);

		ksort($parameter);
		reset($parameter);

		$html = '';
		$html .= '<html>'."\n";
		$html .= '<head>'."\n";
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset='.$input_charset.'" />'."\n";
		$html .= '<title>财付通支付，正在跳转...</title>'."\n";
		$html .= '</head>'."\n";
		$html .= '<body onLoad="document.tenpay.submit();">'."\n";

		$signPars = "";
		$form_content = '';

		foreach ($parameter AS $k => $v)
		{

			$form_content .= "<input type='hidden' name='{$k}' value='".$v."'>\n";
			if("" != $v && "sign" != $k)
			{
				$signPars .= $k . "=" .$v . "&";
			}
		}


		$signPars .= "key=" . $this->payment['key'];
		$sign = strtolower(md5($signPars));

		$html .= "<form name='tenpay' action='https://gw.tenpay.com/gateway/pay.htm' method='post' >\n";
		$html .= $form_content;
		$html .= "<input type='hidden' name='sign' value='".$sign."'>\n";
		//$html .= "<input type='submit' value='确定支付' />\n";
		$html .= "</form>\n";
		$html .= "</body>\n";
		$html .= "</html>\n";

		return $html;
	}

	/**
     * 响应操作
     */
	function respond()
	{

		if (!empty($_POST))
		{
			foreach($_POST as $key => $data)
			{
				$_GET[$key] = $data;
			}
		}

		$payment  = $this->payment;

		/* 检查数字签名是否正确 */
		ksort($_GET);
		reset($_GET);

		$signPars = '';

		foreach($_GET as $k => $v)
		{
			if("sign" != $k && "" != $v && $k != 'code' && $k != 'app'  && $k != 'act')
			{
				$signPars .= $k . "=" . $v . "&";
			}
		}
		$signPars .= "key=" . $payment['key'];

		$sign = strtoupper(md5($signPars));

		if ($sign != $_GET['sign'])
		{

			return -1;//签名不对，这里不写入错误日志，防止同步跳转，别人恶意攻击，写入文件，影响服务器
		}

		//获取远程服务器ATN结果（验证是否发来的消息）
		if($_GET['act']=='async')//异步通知，更新订单状态，必须验证是不是支付接口发过来的请求
		{
			$ret = $this->getResponse($_GET['notify_id']);
			return $ret;
		}
		else  //同步通知只验证前面的签名
		{
			return 1;
		}


	}
	/**
	 * 获取外部交易号
	 */
	function get_out_trade_no()
	{
		return $_REQUEST['out_trade_no'];
	}

	/**
	 * 检查金额是否相符
	 * @param total_price,数据库中的订单金额
	 * @return  void
	 */
	function check_total_fee($total_price)
	{
		$order_amount = ($_GET['total_fee'] + $_GET['discount']) / 100;
		if($total_price == $order_amount)
		return true;
		else
		return false;
	}

	/**
     * 获取订单金额
     */
	function get_total_fee()
	{
		$order_amount = ($_GET['total_fee'] + $_GET['discount']) / 100;

		return $order_amount;
	}
	/*
	通知id验证接口
	$notify_id 通知id
	*/
	function getResponse($notify_id)
	{

		$url = 'https://gw.tenpay.com/gateway/simpleverifynotifyid.xml';
		$fields =array(
		'partner'=>$this->payment['partner'],
		'notify_id'=>$notify_id,
		'input_charset'=>'UTF-8',
		);

		ksort($fields);

		$signPars = '';

		foreach($fields as $k => $v)
		{
			if("sign" != $k && "" != $v )
			{
				$signPars .= $k . "=" . $v . "&";
			}
		}
		$signPars .= "key=" . $this->payment['key'];

		//echo $signPars."<br>";

		$sign = strtolower(md5($signPars));

		//echo $sign;die();

		$fields['sign'] = $sign;

		$xml = $this->post_curl($url,$fields);

//		var_dump($xml);die();

		$xml_obj =  simplexml_load_string($xml);
		$xml_arr =  $this->object2array($xml_obj);

		//print_r($xml_arr);die();

		if($xml_arr['retcode'] == '0' )
		{
			return 1;//成功
		}
		elseif($xml_arr['retcode'] == '88222005' )
		{
			return -2;//表示通知ID超时
		}

		else
		{
			return -3;//验证失败
		}


	}

	function post_curl($url, $fields)
	{
		/*	$fields_string ='';
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&' ; }
		rtrim($fields_string ,'&');
		$ch = curl_init();
		// 设置 curl 相应属性
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
		$returnTransfer = curl_exec($ch);
		curl_close($ch);
		return $returnTransfer;*/

		$ch  =  curl_init();
		$options  =  array(
		CURLOPT_URL=>$url,
		CURLOPT_HEADER=>0,
		CURLOPT_VERBOSE=>0,
		CURLOPT_RETURNTRANSFER=>true,
		CURLOPT_POST=>true,
		CURLOPT_POSTFIELDS=>http_build_query($fields),
		);
		curl_setopt_array($ch,  $options);
		$result  =  curl_exec($ch);
		curl_close($ch);
		return  $result;

	}

	function object2array($object)
	{
		return @json_decode(@json_encode($object),1);
	}
	/**
     *    错误消息
     */
	function error_message($num)
	{
		switch ($num)
		{
			case -1:
				$msg = '签名不对';
				break;
			case -2:
				$msg = '通知ID超时';
				break;
			case -3:
				$msg = '通知ID验证失败';
				break;
		}
		return $msg;
	}

	/**
     *    将验证结果反馈给网关
     *
     *    @author    Garbin
     *    @param     bool   $result
     *    @return    void
     */
	function verify_result($result)
	{
		if ($result)
		{
			echo 'success';
		}
		else
		{
			echo 'fail';
		}
	}

	/**
     *    支付费率
     *    @param  money 订单总额
     */
	function get_pay_rate($money)
	{

		$pay_rate = 0.01;
		return $pay_rate;

	}
}

?>